<template>
  <div class="view-wrapper">
    <div class="tabs-body">
      <div class="view-inner-wrap">
        <div class="title">{{title}}</div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否启用：">
                <el-switch :disabled="disabled" v-model="ruleForm.enableStatus" active-value="1" inactive-value="2"
                  active-text="启用" @change="changeEnableStatus" inactive-text="关闭">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="盲盒类型" prop="activityType" >
                <el-select v-model="ruleForm.activityType" placeholder="全部" size="small" @change="changeActivity" :disabled="disabled">
                  <el-option v-for="item in boxActivityType" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="盲盒背景" prop="type">
                <el-select v-model="ruleForm.type" placeholder="全部" size="small" :disabled ="ruleForm.activityType ==''" >
                  <el-option v-for="item in boxTypeList" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="活动名称：" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请填写活动名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="活动开始时间：" prop="startTime">
                <el-date-picker :disabled="disabled" v-model="ruleForm.startTime" type="datetime"
                  format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="活动结束时间：" prop="endTime">
                <el-date-picker v-model="ruleForm.endTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" :disabled="isEditTime"
                  value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" v-if="ruleForm.activityType == 1">
              <el-form-item label="盲盒失效时间：" prop="expiresTime">
                <el-date-picker v-model="ruleForm.expiresTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" 
                  value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择失效时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 自动开盒盲盒价格逻辑 -->
          <div v-if="ruleForm.activityType == 2">
            <el-form-item label="盲盒价格：" required>
             <!-- 盲盒价格 -->
            <el-row >
              <el-col :span="12">
                  <div class="hang">
                    <el-button type="primary" icon="el-icon-plus" @click="addMoney" :disabled="disabled">添加</el-button>
                    <div class="mar-14">最多可添加3个价格</div>
                  </div>
              </el-col>
            </el-row>

            <div class="moneyList" v-for="(item, index) in ruleForm.priceList" :key="index" style="margin: 20px 0 20px -40px; padding-left: 0;">
              <el-row style="margin-bottom: 20px;">
                <el-col :span="6">
                  <el-form-item label="价格名称：" :prop="'priceList.' + index + '.name'" :rules="rules.priceName">
                    <el-input v-model="item.name" placeholder="请输入" @focus="focusPriceList(item.name)"
                      @change="changePriceList(item.name,index)" :disabled="disabled"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="价格：" :prop="'priceList.' + index + '.price'" :rules="rules.price">
                    <el-input type="number" v-model="item.price" placeholder="请输入" :disabled="disabled">
                      <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="140px" label="盲盒开启数量：" :prop="'priceList.' + index + '.boxAmount'"
                    :rules="rules.boxAmount">
                    <el-input type="number" v-model="item.boxAmount" placeholder="请输入" :disabled="disabled">
                      <template slot="append">个</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="index != 0">
                  <el-button type="danger" icon="el-icon-delete" size="small " round style="margin: 2px 0 0 14px"
                    @click="deleteMoney(index,item.name)" :disabled="disabled"></el-button>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="" required  style="padding-left: 130px;">
                    <el-checkbox :disabled="disabled" true-label="2" false-label="1" v-model="item.useCoupon">
                      是否能够使用盲盒优惠券
                    </el-checkbox>
                  </el-form-item>
                </el-col>
                <template v-if="item.useCoupon == 2">
                  <el-col :span="6">
                    <el-form-item label="用券数量：" :prop="'priceList.' + index + '.couponAmount'" :rules="rules.couponAmount">
                      <el-input type="number" v-model="item.couponAmount" placeholder="请输入" :disabled="disabled">
                        <template slot="append">张</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label-width="140px" label="用券后价格：" :prop="'priceList.' + index + '.discountPrice'"
                      :rules="rules.discountPrice">
                      <el-input type="number" v-model="item.discountPrice" placeholder="请输入" :disabled="disabled">
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </template>
              </el-row>
            </div>
          </el-form-item>
          </div>
          <!-- 手动开盒盲盒逻辑 -->
          <div v-if="ruleForm.activityType == 1">
              <!-- 盲盒价格 -->
              <div v-for="(item, index) in ruleForm.priceList" :key="index">
               <el-row>
                <el-col :span="6">
                  <el-form-item label="盲盒价值：" :prop="'priceList.' + index + '.price'" :rules="rules.price" >
                    <el-input type="number"  v-model="item.price"  placeholder="请输入" :disabled="disabled">
                        <template slot="append">元</template>
                      </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="5">
                  <el-form-item label="" required>
                    <el-checkbox :disabled="disabled" true-label="2" false-label="1" v-model="item.useCoupon" @change="changeUseCoupon">
                      启用盲盒券兑换
                    </el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="item.useCoupon == 2 ">
                    <el-form-item label="用券数量：" :prop="'priceList.' + index + '.couponAmount'" :rules="rules.couponAmount">
                      <el-input type="number" v-model="item.couponAmount" placeholder="请输入" :disabled="disabled">
                        <template slot="append">张</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
              </el-row>
      
              <el-row>
                <el-col :span="5">
                  <el-form-item label="" >
                    <el-checkbox :disabled="disabled" true-label="2" false-label="1" v-model="item.useIntegral" @change="changePointDeduction">
                      启用积分兑换
                    </el-checkbox>
                  </el-form-item>
                </el-col>
                <div v-if="item.useIntegral == 2">
                  <el-col :span="6">
                    <el-form-item label="积分类型：" :prop="'priceList.' + index + '.integralType'" :rules="rules.integralType">
                      <el-select v-model="item.integralType" placeholder="全部" size="small" :disabled="disabled">
                        <el-option v-for="item in integralTypeList" :key="item.id" :label="item.value" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="使用积分数量："  :prop="'priceList.' + index + '.integralUseAmount'" :rules="rules.integralUseAmount">
                      <el-input type="number" v-model="item.integralUseAmount" placeholder="请输入" :disabled="disabled"></el-input>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="6">
                    <el-form-item label="" required label-width="50px" >
                      <el-checkbox :disabled="disabled" true-label="2" false-label="1" v-model="item.mustUseIntegral">
                        必须使用积分抵扣
                      </el-checkbox>
                    </el-form-item>
                  </el-col> -->
                </div>
              </el-row>
            </div>
              <el-row>
                <el-col :span="7">
                  <el-form-item label="盲盒回收价格"  prop="integralRecyclingType" > 
                    <span style="color: #606266;font-size:15px;font-weight: 600;">回收方式：</span>
                    <el-select v-model="ruleForm.integralRecyclingType" placeholder="全部" size="small">
                        <el-option v-for="item in integralTypeList" :key="item.id" :label="item.value" :value="item.id">
                        </el-option>
                      </el-select>
                  </el-form-item>
                </el-col>
                  <el-col :span="6">
                    <el-form-item label="回收价格：" prop="integralRecyclingPrice" >
                      <el-input type="number" v-model="ruleForm.integralRecyclingPrice" placeholder="请输入" ></el-input>
                    </el-form-item>
                  </el-col>
              </el-row>
            
          </div>
          <!-- 盲盒奖品 -->
          <div>
            <el-row>
              <el-col :span="12">
                <el-form-item label="盲盒奖品：" required>
                  <div class="hang">
                    <!-- <el-button type="primary" icon="el-icon-plus" @click="addPrize" :disabled="disabled">添加</el-button> -->
                    <el-button type="primary" icon="el-icon-plus" @click="addDiglog" :disabled="disabled">添加</el-button>

                    <div class="mar-14"><span
                        :class="[realityRatioShow && showRatioShow ? 'hei' : 'red']">盲盒奖品抽取比例合计需要达到100%</span></div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="prizeList" v-for="(item, index) in ruleForm.prizeList" :key="index">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="" :prop="'prizeList.' + index + '.prizeId'" :rules="rules.prizeId">
                    <el-select v-model="item.prizeId" placeholder="请选择" @click.native="focusPrizeList(item.prizeId)"
                      @change="changePrizeList" :disabled="disabled" filterable >
                      <el-option v-for="itema in initPrizeList" :key="itema.id" :label="itema.name" :value="itema.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <!-- <el-form-item label-width="100px" :label="path == 'detail' ? '添加数量': '投放数量'"
                    :prop="'prizeList.' + index + '.amount'" :rules="rules.amount">
                    <el-input type="number" v-model="item.amount" placeholder="请输入">
                      <template slot="append">个</template>
                    </el-input>
                  </el-form-item> -->
                  <el-form-item label-width="100px" label="投放数量" v-if="path != 'detail'"
                    :prop="'prizeList.' + index + '.amount'" :rules="rules.amount">
                    <el-input type="number" v-model="item.amount" placeholder="请输入">
                      <template slot="append">个</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label-width="100px" label="添加数量" v-if="path == 'detail'">
                    <div class="dis_center">
                      <el-input type="number" v-model="item.addAmount" placeholder="请输入" style="width:160px" :disabled="isEditTime"> 
                        <template slot="append">个</template>
                      </el-input>
                      <span>（{{item.amount}}个）</span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item label-width="130px" label="实际抽取比例" :prop="'prizeList.' + index + '.realityRatio'"
                    :rules="rules.realityRatio">
                    <el-input type="number" v-model="item.realityRatio" placeholder="请输入" :disabled="disabled" style="width: 160px" @change="realityRatioCombined">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item label-width="140px" label="显示抽取比例:" :prop="'prizeList.' + index + '.showRatio'"
                    :rules="rules.showRatio">
                    <el-input type="number" v-model="item.showRatio" placeholder="请输入" :disabled="disabled" style="width: 120px" @change="showRatioCombined">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="3" v-if="index != 0">
                  <el-button type="danger" icon="el-icon-delete" size="small " round style="margin: 2px 0 0 14px"
                    @click="deletePrize(index,item.prizeId)" :disabled="disabled"></el-button>
                </el-col>
              </el-row>
            </div>
            <el-row>
              <el-col :span="6">
                <div style="color: #fff">1</div>
              </el-col>
              <el-col :span="5">
                <div style="color: #fff">1</div>
              </el-col>
              <el-col :span="5">
                <div style="padding-left: 30px">合计比例：{{realityRatioTotal}}%</div>
              </el-col>
              <el-col :span="5">
                <div style="padding-left: 30px">合计比例：{{showRatioTotal}}%</div>
              </el-col>
              <el-col :span="3">
                <div style="color: #fff">1</div>
              </el-col>
            </el-row>
          </div>

          <!-- 盲盒逻辑 -->
          <div v-if="ruleForm.activityType == 2">
            <el-row>
              <el-col :span="12">
                <el-form-item label="盲盒逻辑：">
                  <div class="hang">
                    <el-switch :disabled="disabled" v-model="ruleForm.ruleEnableStatus" active-text="是否启用"
                      active-value="1" inactive-value="2">
                    </el-switch>
                    <el-button type="primary" icon="el-icon-plus" @click="addLogic" style="margin-left: 20px"
                      v-if="ruleForm.ruleEnableStatus == 1" :disabled="disabled">添加</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="ruleForm.ruleEnableStatus == 1">
              <div class="logic" v-for="(item,index) in ruleForm.ruleList" :key="index">
                <el-form-item label-width="0px" label="" :prop="'ruleList.' + index + '.name'" :rules="rules.priceId">
                  <div class="inpBox">
                    <div class="mar-r-10">购买</div>
                    <el-select v-model="item.name" placeholder="选择价格名称" :disabled="disabled">
                      <el-option v-for="itema in ruleForm.priceList" :key="itema.name" :label="itema.name"
                        :value="itema.name">
                      </el-option>
                    </el-select>
                  </div>
                </el-form-item>
                <el-form-item label-width="0px" label="" :prop="'ruleList.' + index + '.buyCount'"
                  :rules="rules.buyCount">
                  <div class="inpBox da">
                    <div class="mar-r-10">到达</div>
                    <el-input type="number" v-model="item.buyCount" placeholder="请输入" :disabled="disabled"></el-input>
                  </div>
                </el-form-item>
                <el-form-item label-width="0px" label="" :prop="'ruleList.' + index + '.prizeId'"
                  :rules="rules.prizeId">
                  <div class="inpBox">
                    <div class="mar-r-10">次时，100%，可获得</div>
                    <el-select v-model="item.prizeId" placeholder="选择奖品" :disabled="disabled">
                      <el-option v-for="itema in ruleForm.prizeList" :key="itema.prizeId" :label="itema.name"
                        :value="itema.prizeId">
                      </el-option>
                    </el-select>
                  </div>
                </el-form-item>
                <el-col :span="3" v-if="index != 0">
                  <el-button type="danger" icon="el-icon-delete" size="small " round style="margin: 2px 0 0 14px"
                    @click="deleteLogic(index)" :disabled="disabled"></el-button>
                </el-col>
              </div>
            </div>
          </div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="活动规则:" prop="pictureList">
                <ImageUploadMore :limit="6" :fileSize="20" @successImg="getPictureList" :value="ruleForm.pictureList">
                </ImageUploadMore>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')" v-if="ruleForm.enableStatus == 2"
              :loading="loading">保存草稿</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')" v-if="ruleForm.enableStatus == 1"
              :loading="loading">保存开始</el-button>
            <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
          </el-form-item>
        </el-form>
      </div>
    </div>
    <blindBoxDiglog v-if="dialogVisible" :initPrizeList='initPrizeList' :visible.sync="dialogVisible"
      @success="_handleSuccess" />
  </div>
</template>
<script>
  import {
    prizeSelectList,
    jackpotSelectList,
    addBoxActivity,
    activityDetail,
    editBoxActivity,
    updatePicture,
    adminDict,
  } from '@/api/blindBox'
  import blindBoxDiglog from './activityDetail/blindBoxDiglog'
  export default {
    name: "shopDetail",
    components: {
      blindBoxDiglog
    },

    data() {
      var validateMoney = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入金额'));
        } else {
          callback()
        }
      };
      var validateBoxAmount = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入数量'));
        } else if (value > 10) {
          callback(new Error('最大输入10个'));
        } else {
          callback()
        }
      };
      var validateCouponAmount= (rule, value, callback) => {
        var reg = /(^[1-9]\d*$)/
        if (value === '') {
          callback(new Error('请填写用券数量'));
        } else if (!reg.test(value)) {
          callback(new Error('请填写大于0的整数'));
        }  else {
          callback();
        }
      };
      var checkSellPrice = (rule, value, callback) => { //销售价格校验
        let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (regNumber.test(value) == false || value == '0.00' || value == '0.0') {
          return callback(new Error('请填写大于0且最多保留两位小数的数值'));
        } else {
          return callback()
        }
      };
      var checkRealityRatio= (rule, value, callback) => { 
        let regNumber = /(^[0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (value === '') {
          callback(new Error('请填写'));
        }else if (regNumber.test(value) == false) {
          return callback(new Error('请填写正数'));
        }else {
          return callback()
        }
      };
      var checkShowRatio= (rule, value, callback) => { 
        let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (value === '') {
          callback(new Error('请填写'));
        }else if (regNumber.test(value) == false || value == '0.00' || value == '0.0') {
          return callback(new Error('请填写大于0且最多保留两位小数的数值'));
        }else {
          return callback()
        }
      };
      return {
        startDatePicker: this.beginDate(),
        endDatePicker: this.processDate(),
        title: '新增盲盒活动',
        dialogVisible: false,
        loading: false,
        checked: false,
        disabled: false,
        isEditTime: false,
        eventPrizeId: '',
        eventPriceName: '',
        prizeSelectList: [],
        initPrizeList: [],
        jackpotSelectList: [],
        path: 'add',
        boxTypeList: [],//背景类型
        boxActivityType: [], //活动类型
        integralTypeList:[], //使用积分类型、回收积分类型列表
        ruleForm: {
          date: [],
          enableStatus: "1", //活动启用状态（1启动 2 禁用）
          startTime: '', //	活动开始时间
          endTime: '', //	活动结束时间
          expiresTime:'',//盲盒失效时间
          id: '', //盲盒活动id
          name: '', //活动名称
          pictureList: [], //活动规则图片列表
          status: '2', //活动状态（1草稿、2待开始、3进行中、4已结束）
          type: '', //盲盒背景 
          activityType:'1',//盲盒活动类型
          integralRecyclingType:'',//回收方式
          integralRecyclingPrice:'',//回收价格
          //盲盒价格列表
          priceList: [{
            name: '', //价格名称
            price: '', //价格
            useCoupon: '1', //是否使用优惠券;1 不能使用 2 可使用
            boxAmount: '', //盲盒数量
            couponAmount: '',//优惠券数量
            discountPrice: '',//	用券后价格
            useIntegral:'1',//是否使用积分抵扣
            mustUseIntegral:'1',//必须使用积分抵扣
            integralType:'',//积分类型
            integralUseAmount:'',//积分数量

          }, ],
          //盲盒奖品列表
          prizeList: [{
            name: '',
            amount: '', //	奖品数量
            prizeId: '', // 奖品id
            realityRatio: '', //	实际抽取比例（单位：百分比）
            showRatio: '', // 显示抽取比例（单位：百分比）
            addAmount: '', //添加数量
          }, ],
          //盲盒逻辑列表
          ruleEnableStatus: '1', //盲盒逻辑启用状态（1 启动 2 禁用）
          ruleList: [{
            name: '',
            buyCount: '', //购买次数
            id: '', //盲盒活动规则id
            priceId: '', //盲盒价格id
            prizeId: '', //奖品id
          }],
          //奖池规划列表
          // jackpotEnableStatus: '2', //奖池启用状态（1 启动 2 禁用）

          // jackpotList: [{
          //   accumulateMoney: '', //目标金额
          //   id: '', //	奖池规划id
          //   jackpotPrizeList: [{
          //       amount: '', //开奖数量
          //       id: '', //奖池规划奖品id
          //       jackpotId: '', //	奖池规划id
          //       name: '', //奖项名称
          //       prizeId: '', //奖池奖品id
          //     },

          //   ]
          // }],
        },
        realityRatioShow: true,
        showRatioShow: true,
        isAccumulate: true,
        showRatioTotal: 0,
        realityRatioTotal: 0,
        rules: {
          activityType: [{
            required: true,
            message: '请选择盲盒活动类型',
            trigger: 'change'
          }, ],
          type: [{
            required: true,
            message: '请选择盲盒背景',
            trigger: 'change'
          }, ],
          name: [{
              required: true,
              message: '请填写活动名称',
              trigger: 'blur'
            },
            {
              max: 10,
              message: '最多 10 个字符',
              trigger: 'blur'
            }
          ],
          expiresTime: [{
            required: true,
            message: '请选择失效时间',
            trigger: 'change'
          }],
          startTime: [{
            required: true,
            message: '请选择日期',
            trigger: 'change'
          }],
          priceName: [{
            required: true,
            message: '请输入价格名称',
            trigger: 'blur'
          }, ],
          price: [{
            required: true,
            message: '请输入盲盒价值',
            trigger: 'blur'
          }, 
          {
            validator: checkSellPrice,
             trigger: 'blur'
           },
        ],
          boxAmount: [{
            validator: validateBoxAmount,
            trigger: 'blur'
          }, ],
          amount: [{
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          }, ],
          couponAmount: [{
            required: true,
            validator: validateCouponAmount,
            trigger: 'blur'
          }, ],
          discountPrice: [{
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          }, ],
          prizeId: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }, ],
          realityRatio: [{
            required: true,
            validator: checkRealityRatio,
            trigger: ['change','blur']
          }, ],
          showRatio: [{
            required: true,
            validator: checkShowRatio,
            trigger: ['change','blur']
          }, ],
          priceId: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }, ],
          integralType: [{
            required: true,
            message: '请选择积分类型',
            trigger: 'change'
          }, ],
          integralUseAmount: [{
            required: true,
            message: '请输入积分数量',
            trigger: 'blur'
          },
          {
            validator: checkSellPrice,
             trigger: 'blur'
           }, 
        ],
        integralRecyclingType: [{
            required: true,
            message: '请选择回收方式',
            trigger: 'change'
          }, ],
          integralRecyclingPrice: [{
            required: true,
            message: '请输入回收价格',
            trigger: 'blur'
          }, 
          {
            validator: checkSellPrice,
             trigger: 'blur'
           },
        ],
          buyCount: [{
            required: true,
            message: '请输入',
            trigger: 'blur'
          }, ],
          accumulateMoney: [{
            validator: validateMoney,
            trigger: 'blur'
          }, ],
          jackpotName: [{
            required: true,
            message: '请输入奖项名称',
            trigger: 'blur'
          }, ],
          pictureList: [{
            required: true,
            message: "请上传图片",
            trigger: "blur"
          }],
          endTime: [{
            required: true,
            message: '请选择结束时间',
            trigger: 'change'
          }, ],
        }

      };
    },
    watch: {

    },
    created() {
      this.getActivityType() //获取活动类型
      this.getIntegralTypeList() //使用积分类型、回收积分类型
      this.changeActivity(1) //手动开盒
      this.getprizeSelectList()
      // this.getjackpotSelectList()
      this.path = this.$route.query.type
      this.ruleForm.id = this.$route.query.id
      this.status =  this.$route.query.status
      if (this.path == 'edit') {
        this.title = '编辑盲盒活动'
        this.getDetail()
      } else if (this.path == 'detail') {
        this.title = '查看详情'
        this.getDetail()
        this.disabled = true
      }
      if(this.status == 4){
        this.isEditTime = true
      }
      console.log('this.ruleForm.id', this.ruleForm.id)
    },
    mounted() {

    },
    methods: {
      //获取全部盲盒类型
      getadminDict() {
        const params = {
          dictType: "shenye_box_type",
        };
        adminDict(params).then((res) => {
          this.boxTypeList = res.result[0].dictList;
        });
      },
      //使用积分类型
      getIntegralTypeList() {
        const params = {
          dictType: "box_activity_integral_type",
        };
        adminDict(params).then((res) => {
          this.integralTypeList = res.result[0].dictList;
        });
      },
      changeActivity(e,key = 1) {
        this.$nextTick(function () {
          this.$refs.ruleForm.clearValidate()
        });
        if(this.path == 'add'){
          this.ruleForm.priceList =          
            [{
              name: '', //价格名称
              price: '', //价格
              useCoupon: '1', //是否使用优惠券;1 不能使用 2 可使用
              boxAmount: '', //盲盒数量
              couponAmount: '',//优惠券数量
              discountPrice: '',//	用券后价格
              useIntegral:'1',//是否使用积分抵扣
              mustUseIntegral:'1',//必须使用积分抵扣
              integralType:'',//积分类型
              integralUseAmount:'',//积分数量

          } ]
        }

        if(key == 1){
          this.ruleForm.type = ''
        }
        //获取商户类型字典
        if(e == 2){
          // 自动风格
          const params = {
            dictType: "shenye_auto_box_type",
          };
          adminDict(params).then((res) => {
            this.boxTypeList = res.result[0].dictList;
          });

        }else{
          // 手动风格
          const params = {
            dictType: "shenye_manual_box_type",
          };
          adminDict(params).then((res) => {
            this.boxTypeList = res.result[0].dictList;
          });
        }

      },
      //获取活动类型
      getActivityType() {
        const params = {
          dictType: "box_activity_type",
        };
        adminDict(params).then((res) => {
          this.boxActivityType = res.result[0].dictList;
        });
      },

      beginDate() {
        let self = this
        return {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7; //开始时间不选时，结束时间最大值小于等于当天
          }
        }
      },
      //提出结束时间必须大于提出开始时间
      processDate() {
        let self = this
        return {
          disabledDate(time) {
            console.log('111111111111', new Date(self.ruleForm.startTime).getTime())
            if (self.ruleForm.startTime) {
              return time.getTime() < new Date(self.ruleForm.startTime).getTime() //- 8.64e7;
            } else {
              return time.getTime() < Date.now(); //开始时间不选时，结束时间最小值当天+1
            }
          }
        }
      },
      // 勾选优惠券
      changeUseCoupon(e){
         if(e == 2){
          //  this.ruleForm.priceList[0].useIntegral = '1'
          //  this.ruleForm.priceList[0].mustUseIntegral = '1'
          //  this.ruleForm.priceList[0].integralType = ''
          //  this.ruleForm.priceList[0].integralUseAmount = ''
         }
      },
      // 勾选积分抵扣券
      changePointDeduction(e){
         if(e == 2){
            // this.ruleForm.priceList[0].useCoupon = '1'
            // this.ruleForm.priceList[0].couponAmount = ''
          }
      },
      //格式化选择时间
      getTime(e) {
        console.log("e", e)
        var timeArr = e
        this.ruleForm.startTime = e[0]
        this.ruleForm.endTime = e[1]
        console.log("e", this.ruleForm.startTime)
        console.log("e", this.ruleForm.endTime)
      },

      //活动详情
      getDetail() {
        var id = this.ruleForm.id
        activityDetail(id).then(res => {
          var data = res.result
          // this.ruleForm = {
          //   ...res.result
          // }
          this.ruleForm.enableStatus = res.result.enableStatus
          this.ruleForm.id = res.result.id
          this.ruleForm.name = res.result.name
          this.ruleForm.pictureList = res.result.pictureList
          this.ruleForm.status = res.result.status
          this.ruleForm.type = res.result.type
          this.ruleForm.priceList = res.result.priceList
          this.ruleForm.prizeList = res.result.prizeList
          this.ruleForm.ruleEnableStatus = res.result.ruleEnableStatus
          this.ruleForm.ruleList = res.result.ruleList
          this.ruleForm.activityType = res.result.activityType
          this.ruleForm.integralRecyclingPrice = res.result.integralRecyclingPrice
          this.ruleForm.integralRecyclingType = res.result.integralRecyclingType
          if(res.result.activityType !=''){
            this.changeActivity(this.ruleForm.activityType,2)
          }
          // this.ruleForm.jackpotEnableStatus = '2'
          // this.ruleForm.jackpotList = res.result.jackpotList
          this.ruleForm.startTime = res.result.startTime
          this.ruleForm.endTime = res.result.endTime
          this.ruleForm.expiresTime = res.result.expiresTime
          // this.formatterPrizeList() 
          this.realityRatioCombined()
          this.showRatioCombined()
          setTimeout(() => {
            this.formatterPrizeList()
          }, 1000);
        }).finally(() => {

        })
      },
      // getTime(e){
      //   console.log('e',e)
      //   var endTime = e.split(' ')
      //   this.ruleForm.endTime = endTime[0] + ' ' + endTime[1]+':00:00'
      // },
      //格式化逻辑奖品下拉
      formatterPrizeList() {
        for (var i = 0; i < this.ruleForm.prizeList.length; i++) {
          for (var j = 0; j < this.initPrizeList.length; j++) {
            if (this.ruleForm.prizeList[i].prizeId == this.initPrizeList[j].id) {
              this.ruleForm.prizeList[i].name = this.initPrizeList[j].name
            }
          }
        }
        this.$forceUpdate()
      },
      /* 添加价格 */
      addMoney() {
        // var 
        if (this.ruleForm.priceList.length < 3) {
          var moneyObj = {
            name: '',
            price: '',
            useCoupon: '1',
            boxAmount: '',
          }
          this.ruleForm.priceList.push(moneyObj)
        } else {
          this.$message.warning('最多添加3个价格')
        }
      },
      /* 删除价格 */
      deleteMoney(index, name) {
        this.ruleForm.priceList.splice(index, 1)
        this.eventPriceName = name
        this.formattingName()
      },
      /* 添加奖品 */
      addPrize() {
        var prizeObj = {
          name: '',
          amount: '',
          prizeId: '',
          realityRatio: '',
          showRatio: '',
        }
        this.ruleForm.prizeList.push(prizeObj)
      },
      //实际抽佣比例
      realityRatioCombined(){
        var num = 0
        this.ruleForm.prizeList.forEach(item => {
          if(item.realityRatio){
            num += parseFloat(item.realityRatio)
          }
        })
        this.realityRatioTotal = Math.round(num * 100) / 100
      },
      //显示抽取比例
      showRatioCombined(){
        var num = 0
        this.ruleForm.prizeList.forEach(item => {
          if(item.showRatio){
            num += parseFloat(item.showRatio)
          }
        })
        this.showRatioTotal = Math.round(num * 100) / 100
      },
      /* 添加奖品弹窗 */
      addDiglog() {
        this.dialogVisible = true
      },
      /* 删除奖品 */
      deletePrize(index, prizeId) {
        // this.initPrize()
        console.log('index', index)
        console.log('this.initPrizeList', this.initPrizeList)
        this.initPrizeList = [...this.prizeSelectList]
        this.ruleForm.prizeList.splice(index, 1)
        this.processPrize(prizeId)
        this.realityRatioCombined()
        this.showRatioCombined()
      },
      processPrize(prizeId) {
        console.log('hahaha ')
        this.ruleForm.ruleList.forEach((item, index) => {
          if (item.prizeId == prizeId) {
            console.log('index', index)
            this.ruleForm.ruleList.splice(index, 1)
          }

        })
      },
      /* 添加逻辑 */
      addLogic() {
        var logicObj = {
          buyCount: '', //购买次数
          id: '', //盲盒活动规则id
          priceId: '', //盲盒价格id
          prizeId: '', //奖品id
        }
        this.ruleForm.ruleList.push(logicObj)
      },
      /* 删除逻辑 */
      deleteLogic(index) {
        this.ruleForm.ruleList.splice(index, 1)
      },
      // /* 添加规划 */
      // addPlanning() {
      //   if (this.ruleForm.jackpotList.length < 5) {
      //     var obj = {
      //       accumulateMoney: '', //目标金额
      //       id: '', //	奖池规划id
      //       jackpotPrizeList: [{
      //         amount: '', //开奖数量
      //         id: '', //奖池规划奖品id
      //         jackpotId: '', //	奖池规划id
      //         name: '', //奖项名称
      //         prizeId: '', //奖池奖品id
      //       }, ]
      //     }
      //     this.ruleForm.jackpotList.push(obj)
      //   } else {
      //     this.$message.warning('最多添加5个阶段')
      //   }

      // },
      // /* 删除规划 */
      // deletePlanning(index) {
      //   this.ruleForm.jackpotList.splice(index, 1)
      // },
      // /* 添加奖项 */
      // addMin(index) {
      //   var obj = {
      //     amount: '', //开奖数量
      //     id: '', //奖池规划奖品id
      //     jackpotId: '', //	奖池规划id
      //     name: '', //奖项名称
      //     prizeId: '', //奖池奖品id
      //   }
      //   this.ruleForm.jackpotList[index].jackpotPrizeList.push(obj)
      // },
      // deleteMin(index, childIndex) {
      //   this.ruleForm.jackpotList[index].jackpotPrizeList.splice(childIndex, 1)
      // },
      getPictureList(e) { //图片
        console.log('e', e)
        if (e != '') {
          this.ruleForm.pictureList = e.split(",")
          this.$refs['ruleForm'].clearValidate(['pictureList']);
        } else {
          this.ruleForm.pictureList = []
        }
      },
      // 获取奖品下拉
      getprizeSelectList() {
        prizeSelectList().then(res => {
          this.prizeSelectList = res.result
          this.initPrizeList = [...res.result]
        }).finally(() => {

        })
      },
      // 获取奖池规划奖品下拉
      // getjackpotSelectList() {
      //   jackpotSelectList().then(res => {
      //     this.jackpotSelectList = res.result
      //   }).finally(() => {

      //   })
      // },
      focusPrizeList(e) {
        console.log('e', e)
        this.eventPrizeId = e
        this.initPrize()
      },
      //选择盲盒奖品-
      changePrizeList(e) {
        if (this.eventPrizeId != e && this.eventPrizeId != '') {
          this.processPrize(this.eventPrizeId)
        }
        this.ruleForm.prizeList = this.ruleForm.prizeList.map(aitem => {
          if (aitem.prizeId == e) {
            this.prizeSelectList.map(item => {
              if (item.id == e) {
                aitem.name = item.name
              }
            })
          }
          return aitem
        })
        // this.initPrize()
      },
      // 初始化奖品下拉列表
      initPrize() {
        this.initPrizeList = [...this.prizeSelectList]
        this.initPrizeList = [...this.initPrizeList].filter(x => [...this.ruleForm.prizeList].every(y => y.prizeId !== x
          .id));
      },
      focusPriceList(e) {
        this.eventPriceName = e
      },
      //输入价格名称
      changePriceList(eve, ind) {
        if (this.eventPriceName != '') {
          this.formattingOneName(eve)

        }
      },
      formattingName() {
        this.ruleForm.ruleList.forEach((item, index) => {
          if (item.name == this.eventPriceName) {
            this.ruleForm.ruleList.splice(index, 1)
          }
        })
      },
      formattingOneName(eve) {
        this.ruleForm.ruleList.forEach((item, index) => {
          if (item.name == this.eventPriceName) {
            item.name = eve
          }
        })
      },
      changeEnableStatus(e) {
        console.log('e', e)
        if (e == 1) {
          this.ruleForm.status = 2
        } else if (e == 2) {
          this.ruleForm.status = 1
        }
      },
      /* 计算实际抽佣比例 */
      changeRealityRatio() {
        var num = 0
        this.ruleForm.prizeList.forEach(item => {
          num += parseFloat(item.realityRatio)
        })
        num = Math.round(num * 100) / 100
        console.log('num', num)
        if (num != 100) {
          this.realityRatioShow = false
        } else {
          this.realityRatioShow = true
        }
        return this.realityRatioShow
      },
      changeshowRatio() {
        console.log('this.ruleForm.prizeList', this.ruleForm.prizeList)
        var num = 0
        this.ruleForm.prizeList.forEach(item => {
          num += parseFloat(item.showRatio)
        })
        num = Math.round(num * 100) / 100
        console.log('num', num)
        if (num != 100) {
          this.showRatioShow = false
        } else {
          this.showRatioShow = true
        }
        return this.showRatioShow
      },
      //阶段价格
      // changeAccumulateMoney() {
      //   console.log(' this.ruleForm.jackpotList', this.ruleForm.jackpotList)
      //   this.ruleForm.jackpotList.forEach((item, index) => {
      //     if (index < this.ruleForm.jackpotList.length - 1) {
      //       if (parseFloat(this.ruleForm.jackpotList[index + 1].accumulateMoney) < parseFloat(this.ruleForm
      //           .jackpotList[index].accumulateMoney)) {
      //         this.isAccumulate = false
      //         console.log('11111111')
      //       } else {
      //         this.isAccumulate = true
      //         console.log('222222')
      //       }
      //     }
      //   })
      //   return this.isAccumulate
      // },
      // 点击提交
      submitForm(formName) {
        // this.changeAccumulateMoney()
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true
            var Reality = this.changeRealityRatio()
            var showRatio = this.changeshowRatio()
            // var isAccumulate = this.changeAccumulateMoney()
            // console.log('isAccumulate', isAccumulate)
            if (!Reality || !showRatio) {
              this.loading = false
              this.$message.error('盲盒奖品抽取比例合计需要达到100')
              return
            }
            // if (!isAccumulate) {
            //   this.loading = false
            //   this.$message.error('奖池规划要按价格从低到高来添加')
            //   return
            // }
            if (this.path == 'add') {

              var data = JSON.parse(JSON.stringify(this.ruleForm));  //深拷贝
                  if(data.activityType == 1){
                      data.ruleEnableStatus = '2'
                      if(data.priceList[0].useIntegral== '1' && data.priceList[0].useCoupon== '1'){
                        this.$message.error('积分和盲盒券兑换不能都为空')
                        this.loading = false
                        return false
                      }
                  }
              addBoxActivity(data).then(res => {
                  this.handleSuccess("创建成功")
                  this.loading = false
                }).catch(() => {
                  this.loading = false
                })
                .finally(() => {

                })
            } else if (this.path == 'edit') {
                  if(this.ruleForm.status == 1 && this.ruleForm.enableStatus == 1){
                      this.ruleForm.status = 2
                  }
                  var data = {
                    ...this.ruleForm
                  }
                editBoxActivity(data).then(res => {
                    this.handleSuccess("编辑成功")
                    this.loading = false
                  }).catch(() => {
                    this.loading = false
                  }).finally(() => {

                  })
            } else if (this.path == 'detail') {
              var data = {
                endTime: this.ruleForm.endTime,
                prizeList: this.ruleForm.prizeList,
                type: this.ruleForm.type,
                name: this.ruleForm.name,
                id: this.ruleForm.id,
                pictureList: this.ruleForm.pictureList
              }
              if(this.ruleForm.activityType == 1){
                data.expiresTime = this.ruleForm.expiresTime
                data.integralRecyclingType = this.ruleForm.integralRecyclingType
                data.integralRecyclingPrice = this.ruleForm.integralRecyclingPrice
              }
              updatePicture(data).then(res => {
                this.handleSuccess("编辑成功")
                this.loading = false
              }).catch(() => {
                this.loading = false
              }).finally(() => {

              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handleSuccess(msg) {
        if (msg === '已拒绝') {
          var type = 'error'
        } else {
          var type = 'success'
        }
        this.$message({
          message: msg,
          type: type,
          duration: 1500,
          // onClose: () => {
          //   this.handleClose('ruleForm')
          // }
        })
        this.$router.push({
          path: '/blindBox/blindBox-list'
        })
      },
      _handleSuccess(e) {
        //成功回调
        // this.resetQuery()
        // this.getList()
        console.log('e', e)
        var list = []
        this.ruleForm.prizeList.forEach(item => {
          try {
            Object.keys(item).forEach(key => {
              if (item[key] != '') {
                list.push(item)
                throw new Error()
              }
            })
          } catch {

          }
        })
        this.ruleForm.prizeList = list.concat(e)
        this.realityRatioCombined()
        this.showRatioCombined()
      },
    },
  };

</script>
<style lang="scss" scoped>
  .tabs-body {
    background-color: #fff;
    padding: 20px 0;
  }

  .title {
    font-size: 24px;
    padding: 14px 30px 30px 30px;
    color: #222;
    font-weight: 500;

  }
  .dis_center{
    display: flex;
    align-items: center;
  }
  .hang {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .mar-14 {
    margin-left: 14px;
  }

  .mar-r-10 {
    margin-right: 14px;
  }

  .moneyList {
    padding-left: 80px;
  }


  .logic {
    display: flex;
    justify-content: flex-start;
    padding-left: 80px;
  }

  .inpBox {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .da {
    .el-input {
      width: 80px;
    }
  }

  .planning {
    padding-left: 80px;
  }

  .hei {
    color: #606266;
  }

  .red {
    color: #ff4949;
  }

  ::v-deep input::-webkit-outer-spin-button,
  ::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
  }

  ::v-deep input[type='number'] {
    -moz-appearance: textfield !important;
  }

  .planning,
  .prizeList {
    .el-select {
      width: 100%;
    }
  }

</style>
